package documents

import (
	"gin-gorm-project/modules"
)

type Documents struct {
	Id      int    `gorm:"type:bigint(20);column:id;primary_key"`
	Title   string `gorm:"type:varchar(64);column:title"`
	Content string `gorm:"type:text;column:content"`
	Blurb   string `gorm:"type:varchar(64);column:blurb"`
}

// InitTable 使用gorm创建表
func InitTable() error {
	err := modules.DB.AutoMigrate(&Documents{})
	if err != nil {
		return err
	}
	return nil
}

func (documents *Documents) TableName() string {
	return "documents"
}

func (documents *Documents) QueryAll() []Documents {
	var blogs []Documents
	modules.DB.Find(&blogs)
	return blogs
}

func (documents *Documents) Query(pageNumber, pageSize int) []Documents {
	var blogs []Documents
	// TODO query by input
	dbUtil := modules.DB
	if len(documents.Title) != 0 {
		dbUtil = dbUtil.Where("title like ?", "%"+documents.Title+"%")
	}
	if len(documents.Content) != 0 {
		dbUtil = dbUtil.Where("content like ?", "%"+documents.Content+"%")
	}
	if len(documents.Blurb) != 0 {
		dbUtil = dbUtil.Where("blurb like ?", "%"+documents.Blurb+"%")
	}
	dbUtil.Limit(pageSize).Offset((pageNumber - 1) * pageSize).Find(&blogs)
	return blogs
}

func (documents *Documents) Save() {
	modules.DB.Save(documents)
}

func (documents *Documents) QueryById() {
	modules.DB.First(documents, documents.Id)
}
